/*
 * @Author: wuyuxin
 * @Date: 2024-06-20 14:07:17
 * @LastEditors: wuyuxin
 * @LastEditTime: 2024-06-26 18:12:15
 * @Description:
 */
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios'
import type { YXRequestConfig } from './type'

class YXRequest {
  // 1.a. 定义实列变量 引入axios类型
  instance: AxiosInstance

  // 1.b 定义实例传参
  constructor(config: YXRequestConfig) {
    // 1.创建实例
    this.instance = axios.create(config)

    // 3.每个instance实例添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        return res.data
      },
      (err) => {
        return err
      }
    )

    // 7.自定义拦截器触发
    // 针对特定的hyRequest实例添加拦截器
    this.instance.interceptors.request.use(
      config.interceptors?.requestSuccessFn,
      config.interceptors?.requestFailureFn
    )
    this.instance.interceptors.response.use(
      config.interceptors?.responseSuccessFn,
      config.interceptors?.responseFailureFn
    )
  }

  // 2.封装request请求
  // 10.设置传入返回值泛型
  request<T = any>(config: YXRequestConfig<T>) {
    // 8.单次请求的成功拦截处理
    if (config.interceptors?.requestSuccessFn) {
      console.log(config, '=====???')
      config = config.interceptors.requestSuccessFn(
        config as InternalAxiosRequestConfig
      )
    }

    return new Promise<T>((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 9.单次请求响应的失败拦截处理
          if (config.interceptors?.responseSuccessFn) {
            res = config.interceptors.responseSuccessFn(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get<T = any>(config: YXRequestConfig<T>) {
    return this.request({ ...config, method: 'GET' })
  }
  post<T = any>(config: YXRequestConfig<T>) {
    return this.request({ ...config, method: 'POST' })
  }
  delete<T = any>(config: YXRequestConfig<T>) {
    return this.request({ ...config, method: 'DELETE' })
  }
  patch<T = any>(config: YXRequestConfig<T>) {
    return this.request({ ...config, method: 'PATCH' })
  }
}

export default YXRequest
